<?php
/** 
 * @package AMFramework
 * @subpackage Core
 * @author Marcu Alexandru
 * @version 1.0 $Build 305b  
 */
defined('_INDEX') or die('Restricted');

class Amfw_Template extends Amfw_Object implements Amfw_Template_ITemplate
{
	protected $_templateName = null;
	protected $_selectedPattern = '';
	
	public function __construct() { $this->__initAll(); }
	protected function _initName()
	{
		if(defined('MAIN_TMPL')):
			$this->_templateName = MAIN_TMPL; // Initialize with default defined value;
		else: trigger_error("<U>You should probably define the default template</U> name <br/>
							by defining the MAIN_TMPL constant in the <B>Incl/Defines.php</B>", E_USER_NOTICE );
		endif;
	}
	// Public ====================================================================
	public static function getInstance()
	{	// Singleton method
		static $instance;
		if(is_null($instance)):
			$instance = self::_create();
			endif;
		return $instance;
	}
	public function setName($name)
	{	// ITemplate
		$previousName = $this->_templateName;
		$this->_templateName = $name;

		// Just for the sake of having a sexy setter
		return $previousName;
	}
	public function setPattern($pattern)
	{
		$prev = $this->_selectedPattern;
		$this->_selectedPattern = $pattern;
		return $prev;
	}
	public function display()
	{	// ITemplate
		$pattern = empty($this->_selectedPattern) ? 'default' : $this->_selectedPattern;
		$tmpl = $this->_createConcreteTemplate();
		if(isset($tmpl))
		{
			$parser = Amfw_Template_Parser::getInstance();
			//TODO: Accept that a layout cannot and should not enforce a pattern!
			//Aici ar trebui sa se cunoasca deja patternul dar nu se cunoaste pentru ca in layout poate
			// fi declarat alt pattern
			$phtml = $parser->parseTemplate($tmpl,$pattern);
			//We choose to echo it here, after parse;
			//TODO: This should be split into another interface which separates parse from display
			//TODO: Reusable for caching
			return $phtml;	//TODO: AICI E SINGURUL FIR DE AFISARE SI AR TREBUI FACUT CAT MAI TARZIU
		}
		else trigger_error("<b>No template was found.</b>", E_USER_WARNING);
	}
	// Private ====================================================================
	private function &_createConcreteTemplate() 
	{	// Creates an instance of the concrete template;
		static $instance;
		$tmpl = $this->_templateName;
		if(isset($tmpl) && is_null($instance)) 
		{
			fwimport(TMPL_PATH . DS . $tmpl . DS . $tmpl . '.php');
			$instance = new $tmpl();
			return $instance;
		}
		return $instance;
	}
	private static function _create()
	{	// Creation method for Singleton.
		return new Amfw_Template();
	}
}